<template>
  <el-dialog v-model="visible" title="枚举添加" :close-on-click-modal=false :destroy-on-close=true>
    <el-form :model="EnumForm" label-width="80px" ref="EnumAddRef">
      <el-form-item label="名称" prop="name">
        <el-input v-model="EnumForm.name"/>
      </el-form-item>
      <el-form-item label="枚举标签" prop="label">
        <el-input v-model="EnumForm.label" />
      </el-form-item>
      <el-form-item label="枚举选项" prop="options">
        <el-col :span="24">
          <el-button @click="addEnumForm" >+ 添加键值对</el-button>
        </el-col>
        <el-row 
          v-for="(item, index) in EnumForm.options" 
          :key="index" :gutter="10" style="margin-bottom: 1%;">
          <el-col :span="6">
            <el-input v-model="item.key" placeholder="标签"></el-input>
          </el-col>
          <el-col :span="6">
            <el-input v-model="item.value" placeholder="值"></el-input>
          </el-col>
          <el-col :span="6">
            <el-input v-model="item.description" placeholder="描述"></el-input>
          </el-col>
          <el-col :span="6">
            <el-button @click="delEnumForm(index)" type="primary">-</el-button>
          </el-col>
        </el-row>
        </el-form-item>
      </el-form>
    <el-button type="primary" @click="save">保存</el-button>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import apiEnum from '@/api/system/enum'

const visible = ref(false)
const props = defineProps({modelValue: Boolean})
const emit = defineEmits(['update:modelValue', 'success'])

const EnumAddRef = ref()
const EnumForm = ref({
  name: '',
  label: '',
  options: []
})

watch(() => props.modelValue, (val) => {
  visible.value = val
})

watch(visible, (val) => {
  emit('update:modelValue', val)
})

const addEnumForm = () => {
  EnumForm.value.options.push({ key: '', value: '' })
}

const delEnumForm = (idx: number) => {
  EnumForm.value.options.splice(idx, 1)
}

const save = () => {
  try {
    const resp = apiEnum.addEnum(EnumForm.value)
    visible.value = false
    EnumForm.value = {
      name: '',
      label: '',
      options: []
    }
    emit('success')
  } catch (error) {
    console.error('保存枚举数据失败:', error)
  }
}

</script>

<style>
</style>
